package x.ovo.wechat.bot.http.request.contact;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import x.ovo.wechat.bot.common.Constant;
import x.ovo.wechat.bot.common.entity.Recommend;
import x.ovo.wechat.bot.common.http.request.ApiRequest;
import x.ovo.wechat.bot.common.http.session.LoginSession;

import java.util.Map;
import java.util.function.Function;

/**
 * 验证请求
 *
 * @author ovo on 2024/05/06.
 * @since 1.0.0
 */
public class VerifyRequest extends ApiRequest<Boolean> {

    private final Recommend recommend;

    public VerifyRequest(LoginSession session, Recommend recommend) {
        super(session);
        this.recommend = recommend;
    }

    @Override
    public String getUrl() {
        return UrlBuilder.of(this.session.getUrl())
                .addPath(Constant.VERIFY)
                .addQuery("r", System.currentTimeMillis())
                .addQuery("lang", "zh_CN")
                .addQuery("pass_ticket", this.session.getPassTicket())
                .build();
    }

    @Override
    public Map<String, Object> getParameters() {
        JSONArray array = JSONUtil.createArray();
        array.add(JSONUtil.createObj()
                .set("Value", recommend.getUserName())
                .set("VerifyUserTicket", recommend.getTicket())
        );
        return JSONUtil.createObj()
                .set("Opcode", 3)
                .set("SceneList", CollUtil.newArrayList(33))
                .set("SceneListCount", 1)
                .set("VerifyContent", "")
                .set("VerifyUserList", array)
                .set("VerifyUserListSize", 1)
                .set("skey", this.session.getSKey());
    }

    @Override
    public String getMethod() {
        return "POST";
    }

    @Override
    public boolean isJson() {
        return true;
    }

    @Override
    public Function<String, Boolean> responseHandler() {
        return s -> JSONUtil.parseObj(s).getJSONObject("BaseResponse").getInt("Ret") == 0;
    }
}
